package me.zhengjie.modules.partner.rest;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.handler.ApiResponse;
import me.zhengjie.modules.partner.service.TokenService;
import me.zhengjie.modules.partner.service.dto.TokenDto;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @className TokenController
 * @description Token生成类
 * @author jianyongjie@126.com
 * @date 2021/8/3 11:52 上午
 * @version 1.0.0
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "商户：Token管理", hidden = true)
@RequestMapping("/api/v1/token")
@Slf4j
public class TokenController {

    @Resource
    private TokenService tokenService;

    /**
     * 商户获取Token
     * @param dto
     * @return
     */
    @Log("商户获取Token")
    @AnonymousPostMapping
    public ApiResponse<TokenDto> createToken(@RequestBody TokenDto dto) {
        try {
            final TokenDto token = tokenService.createToken(dto.getAppId(), dto.getAppSecret());
            return ApiResponse.data(token);
        } catch (BadRequestException e) {
            log.error(e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ApiResponse.error("获取Token失败");
        }
    }

    /**
     * Token 验证
     * @param dto
     * @return
     */
    @AnonymousPostMapping("/verify")
    public ApiResponse<String> verifyToken(@RequestBody TokenDto dto) {
        try {
            return ApiResponse.data(tokenService.verifyToken(dto.getAppId(), dto.getToken()));
        } catch (BadRequestException e) {
            log.error(e.getMessage(), e);
            return ApiResponse.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ApiResponse.error("获取Token失败");
        }
    }
}
